package at.playbox.server.endpoints;

import java.io.ByteArrayInputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingType;
import javax.xml.ws.Provider;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPBinding;
import javax.xml.ws.http.HTTPException;

import at.playbox.server.businesslogic.AuthenticationService;
import at.playbox.server.businesslogic.UserService;

@WebServiceProvider
@BindingType(value = HTTPBinding.HTTP_BINDING)
public class UserChangePassword implements Provider<Source>
{

	@Resource
	protected WebServiceContext wsContext;

	@SuppressWarnings("unchecked")
	public Source invoke(Source source)
	{
		try
		{
			AuthenticationService authService = new AuthenticationService();
			MessageContext mc = wsContext.getMessageContext();
			HttpServletRequest request = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
			Map<String, String> parameters = request.getParameterMap();
			if (parameters.containsKey("username") && parameters.containsKey("hash") && parameters.containsKey("salt"))
			{
				String username = request.getParameter("username");
				String hash = request.getParameter("hash");
				String salt = request.getParameter("salt");

				if (authService.isAuthenticated(mc))
				{

					UserService service = new UserService();
					String result = service.createXML(service.changePassword(username, salt, hash));
					return new StreamSource(new ByteArrayInputStream(result.getBytes()));
				}
				else
				{
					throw new RuntimeException("authentication is needed");
				}
			}
			else
			{
				throw new HTTPException(404);
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new HTTPException(500);
		}
	}

}
